package com.volcreate.inn.controller.admin;

import com.volcreate.inn.po.Tag;
import com.volcreate.inn.service.impl.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;




/**
 * @author zxc
 * @version 0.0.1
 * @date 2020/8/19
 */
@Controller
@RequestMapping("/admin")
public class ATagController {

    private static final String EDIT = "admin/category-tag-edit";
    private static final String LIST = "admin/category-tag";
    private static final String REDIRECT_LIST = "redirect:/admin/tag";

    private final TagService tagService;

    public ATagController(TagService tagService) {
        this.tagService = tagService;
    }


    @GetMapping("/tag")
    public String paraList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                           Model model) {
        model.addAttribute("page", tagService.listByGmtModifiedDesc(page, 2));
        return LIST;
    }

    @GetMapping("/tag/edit")
    public String edit(Model model) {
        model.addAttribute("tag", new Tag());
        return EDIT;
    }


    // 通过category-tag发起的Get请求
    @GetMapping("/tag/{id}/edit")
    public String modify(@PathVariable Long id, Model model) {
        // tag用于传递默认表单属性,和校验用的一样
        model.addAttribute("tag", tagService.getById(id));
        return EDIT;
    }

    @PostMapping("/tag")
    public String psot(Tag tag, BindingResult result, RedirectAttributes attributes) {

        // 存在的，名字为空的，修改id号的操作都不允许。
        String name = tag.getName().trim();
        if (name == null || "" == name) {
            result.rejectValue("name", "tagIsEmpty", "标签不能为空");
        }
        // 判断标签是否存在
        Tag tagByName = tagService.getByName(name);
        if (tagByName != null) {
            result.rejectValue("name", "tagExist", "标签存在");
        }

        // 不能重定向，否则就没有值，将输出的错误带回
        if (result.hasErrors()) {
            return EDIT;
        }

        boolean t;
        if (tag.getId() == null){
            t = tagService.save(tag);
        }else {
            t = tagService.updateById(tag);
        }
        if (t) {
            attributes.addFlashAttribute("message", "操作成功");
        } else {
            attributes.addFlashAttribute("message", "操作失败");
        }
        return REDIRECT_LIST;
    }

    @GetMapping("/tag/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {
        tagService.removeById(id);
        attributes.addFlashAttribute("message", "删除成功");
        return REDIRECT_LIST;
    }

}
